var tools = require('../utils/utils.js');
var moment = require('moment');
var request = require('request')
module.exports = function() {
    return function(model) {
        var model = model;
        this.save = function(camp, cb) {
            camp.createTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
            camp._id = tools.guid();
            var entity = new model(camp);
            entity.save(function(err) {
                tools.execCB(cb, err, null);
            });
        };
        this.remove = function(conditions, cb) {
            model.remove(conditions, function() {
                tools.execCB(cb, err, null);
            });
        };
        this.removeById = function(id, cb) {
            model.remove({ _id: id }, function() {
                tools.execCB(cb, err, null);
            });
        };
        this.update = function(conditions, objNew, option, cb) {
            var option = option || {};
            model.update(conditions, objNew, option, function(err) {
                tools.execCB(cb, err, null);
            });
        };
        this.find = function(conditions, cb) {
            model.find(conditions, function(err, result) {
                tools.execCB(cb, err, result);
            });
        };
        this.findById = function(id, cb) {
            model.find({ _id: id }, function(err, result) {
                tools.execCB(cb, err, result);
            });
        };
        this.findByOpenId = function(id, cb) {
            model.find({ openid: id }, function(err, result) {
                tools.execCB(cb, err, result);
            });
        };
        this.isSubscribed = function(token, openid, _callback) {
            console.log("88888:"+token)
            var _url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token;
            var openids;
            var subscribe;
            request({
                url: _url
            }, function(err, res, body) {
                if (err) {
                    tools.execCallBack(_callback, err);
                } else {
                    console.log("999999:"+JSON.parse(body).data);
                    openids = JSON.parse(body).data.openid;
                    if (openids.indexOf(openid) == -1) {
                        subscribe = 0;
                    } else {
                        subscribe = 1;
                    }
                    tools.execCallBack(_callback, subscribe);
                }
            });
        }
        return this;
    }
}
